package com.atguigu.xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

/**
 * Date:2020/9/4
 * Author:ybc
 * Description:
 */
public class SaxReadTest {

    public static void main(String[] args) throws Exception {
        testMoreElement();
    }

    public static void testMoreElement() throws Exception{
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read("day05_xml/user.xml");
        //获取根标签
        Element rootElement = document.getRootElement();
        //获取xml中所有的userInfo
        List userInfoElements = rootElement.elements("userInfo");
        for (Object o : userInfoElements) {
            Element userInfoElement = (Element) o;
            //获取userInfo中的id属性
            Attribute idAttribute = userInfoElement.attribute("id");
            //获取userInfo下的子标签username、sex、age
            Element usernameElement = userInfoElement.element("username");
            Element sexElement = userInfoElement.element("sex");
            Element ageElement = userInfoElement.element("age");
            //获取标签中存储的数据
            System.out.println(idAttribute.getText());
            System.out.println(usernameElement.getText());
            System.out.println(sexElement.getText());
            System.out.println(ageElement.getText());
        }
    }

    public static void testSingleElement() throws Exception{
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read("day05_xml/user.xml");
        //获取根标签
        Element rootElement = document.getRootElement();
        //获取根标签下的userInfo
        Element userInfoElement = rootElement.element("userInfo");
        //获取userInfo中的id属性
        Attribute idAttribute = userInfoElement.attribute("id");
        //获取userInfo下的子标签username、sex、age
        Element usernameElement = userInfoElement.element("username");
        Element sexElement = userInfoElement.element("sex");
        Element ageElement = userInfoElement.element("age");
        //获取标签中存储的数据
        System.out.println(idAttribute.getText());
        System.out.println(usernameElement.getText());
        System.out.println(sexElement.getText());
        System.out.println(ageElement.getText());
    }

}
